package operatorLogs

import (
	"app/daos"
	. "app/utils"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"time"
)

func init() {
	go flush()
}

type LogCollector struct {
	logChan  chan daos.Logs
	logCache map[string]daos.Logs
	ticker   *time.Ticker
}

var collector = &LogCollector{
	logChan:  make(chan daos.Logs, 50),
	logCache: make(map[string]daos.Logs),
	ticker:   time.NewTicker(2 * time.Second),
}

func Collect(c *gin.Context, response gin.H) {
	var log daos.Logs
	sessionId := c.GetHeader("SESSION-ID")

	obj, _ := c.Get("requestData")
	if obj != nil {
		var jsonMap = Byte2JsonMap(obj)
		if sessionId == "" { //登录
			username, ok := jsonMap["username"]
			if ok {
				log.Username = username.(string)
			} else {
				log.Request = string(obj.([]byte))
			}
		} else {
			log.Request = string(obj.([]byte))
		}
	}

	if sessionId != "" {
		log.Username, _ = SessionMagage.GetSessionVal(sessionId, "username").(string)
	}

	log.IP = c.ClientIP()
	log.UserAgent = c.GetHeader("User-Agent")
	log.Method = c.Request.Method
	log.Url = c.Request.URL.Path
	res, _ := json.Marshal(response)
	log.Response = string(res)
	timeN := daos.Time(time.Now())
	log.CreatedAt = &timeN
	if response["errCode"] == 0 {
		log.Success = 1
	}

	collector.logChan <- log
}

func flush() {
	for {
		select {
		case log := <-collector.logChan:
			collector.logCache[log.Username+log.Url+log.CreatedAt.Format()] = log
			if len(collector.logCache) > 20 {
				for _, v := range collector.logCache {
					_ = daos.GetConnection().Create(&v)
				}

				collector.logCache = make(map[string]daos.Logs)
			}

			break
		case <-collector.ticker.C:
			if len(collector.logCache) == 0 {
				break
			}

			for _, v := range collector.logCache {
				_ = daos.GetConnection().Create(&v)
			}

			collector.logCache = make(map[string]daos.Logs)
		}
	}
}
